<template>
    <section class="todoapp">
    <TodoHeader :list="list" @addTask="addTaskFn" @checkAll="checkAll"></TodoHeader>
    <!-- 把list变成定义的showlist -->
    <TodoMain :list="showList" @del="shangChu"></TodoMain> <!-- 在父组件里面的子组件标签上添加自定义属性 -->
    <TodoFooter
    :list="list"
      @clear="clearFn"
      :type="type"
      @changeType="changeTypeFn">
      </TodoFooter>
  </section>
</template>

<script>
/* 引入css文件 */
import './styles/base.css'
import './styles/index.css'

/* 引入子组件 */
import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data(){
    return {
       list: JSON.parse(localStorage.getItem('todolist')) || [],   /* 取出数据 */
    //  list:[
    //    { id: 100, name: "吃饭", isDone: true },
    //     { id: 101, name: "睡觉", isDone: false },
    //     { id: 102, name: "打豆豆", isDone: true },
    //  ],
     type:'all'
    }
  },
  methods: {
       changeTypeFn(type) {
      this.type = type
    },
    clearFn() {
      // 清除已完成
      this.list = this.list.filter((item) => !item.isDone)
    },
 shangChu(id){
  /* 删除事件 */
   this.list = this.list.filter((item) => item.id !== id)
 },
     addTaskFn(task) {
      /* 回车添加事件 */
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
     checkAll(val) {
      /* 反选 */
      this.list.forEach((item) => (item.isDone = val))
    },
  },
   watch: {
    /* 监听事件 */
    list: {
      deep: true,  /* 深度监听 */
      handler(newVal) {  /* 打开页面立即执行 */
        localStorage.setItem('todolist', JSON.stringify(newVal)) /* 存储到本地 */
      },
    },
  },
    computed: {
      /* 定义的showlist 当type值改变履行对应的 */
    showList() {
      if (this.type === 'yes') {
        return this.list.filter((item) => item.isDone)
      } else if (this.type === 'no') {
        return this.list.filter((item) => !item.isDone)
      } else {
        return this.list
      }
    },
  },
}
</script>
